import { UploadFileInfo } from '@midwayjs/busboy';
import { Inject, Provide, Config, Init } from '@midwayjs/core';
import { uuidv7 } from 'uuidv7';
import { GetFileExtension } from './originelFileName';
import * as Minio from 'minio';

@Provide()
export class MinioService {
    @Config('minioConfig') // 动态注入配置
    minioConfig: any;

    @Inject()
    getFileExtension: GetFileExtension;

    minioClient: Minio.Client;
    bucket: string;

    @Init()
    async init() {
        // 在Init生命周期中初始化，确保配置已经被注入
        this.minioClient = new Minio.Client({
            endPoint: this.minioConfig.intranetPath,
            port: this.minioConfig.port,
            useSSL: this.minioConfig.useSSL,
            accessKey: this.minioConfig.accessKey,
            secretKey: this.minioConfig.secretKey,
        });
        this.bucket = this.minioConfig.bucket;
    }

    async minioUpload(files: Array<UploadFileInfo>, name: string = ''): Promise<string> {
        try {
            const originalFilename = this.getFileExtension.getFileExtension(files);
            let filename: string;
            if (name) {
                filename = name + '.' + originalFilename;
            } else {
                filename = uuidv7() + '.' + originalFilename;
            }
            await this.minioClient.fPutObject(this.bucket, filename, files[0].data);
            const url = `https://${this.minioConfig.endPoint}/${this.bucket}/${filename}`;
            return url;
        } catch (error) {
            console.error(error);
            throw new Error('上传失败');
        }
    }
}